//
//  ZJKUserAccountViewModel.swift
//  MicroBlog
//
//  Created by VAD on 16/4/19.
//  Copyright © 2016年 朱江坤. All rights reserved.
//

import UIKit

import SVProgressHUD

class ZJKUserAccountViewModel: NSObject {
    
    //将viewModel设置成单例
    static let sharedViewModel:ZJKUserAccountViewModel = ZJKUserAccountViewModel()
    
    override init() {
        super.init()
        //再当前viewModel初始化的时候就尝试去沙盒中读取数据
        account = self.accountInSanBox()
        
        
    }
    //当前登录的用户的账户信息
    var account: ZJKUserAccount?
    
    var accessToken: String?{
        
        return self.account?.access_token
    }
    
    var isLogin: Bool{
        
        //判断是否有accessToken
        if accessToken == nil{
            return false
        }
        
        //取到过期时间
        guard let expiresDate = self.account?.expiresDate else{
            return false
        }
        
        //把过期时间与当前时间进行对比
        if NSDate().compare(expiresDate) == .OrderedAscending {
            
            //没有过期就返回true(代表登录)
            return true
        }
        return false
    }
    
    func loadAccessToken(code: String, finished: (isSucess: Bool)->()){
        
        //请求地址
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        
        /**
         
         必选	类型及范围	说明
         client_id	true	string	申请应用时分配的AppKey。
         client_secret	true	string	申请应用时分配的AppSecret。
         grant_type	true	string	请求的类型，填写authorization_code
         
         grant_type为authorization_code时
         必选	类型及范围	说明
         code	true	string	调用authorize获得的code值。
         redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
         
         */
        
        let params = [
            "client_id": WB_APP_KEY,
            "client_secret": WB_APP_SECRET,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WB_REDIRECT_URI
        ]
        
        //发起请求
        HMNetworkTools.sharedTools.request(.Post, urlString: urlString, parameters: params) { (responseObject, error) -> () in
            
            if error != nil{
                print(error)
                
                //请求accessToken失败
                finished(isSucess: false)
                
                return
            }
            
            guard let dict = responseObject as? [String: AnyObject] else{
                print("后台返回的数据格式不对")
                
                finished(isSucess: false)
                return
            }
            
            //进行字典转模型
            let account = ZJKUserAccount(dict: dict)
            
            print(account)
            
            //accessToken获取到了,通过它获取个人信息
            self.loadUserInfo(account, finished: finished)
            
        }
    }
    
    //获取个人信息
    private func loadUserInfo(account: ZJKUserAccount, finished: (isSucess: Bool)->()){
        
        // 请求地址
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        // 请求参数
        let params = [
            "access_token": account.access_token ?? "",
            "uid": account.uid ?? ""
        ]
        //发送请求
        HMNetworkTools.sharedTools.request(urlString: urlString, parameters: params) { (responseObject, error) -> () in
            if error != nil{
                
                finished(isSucess: false)
                
                return
            }
            
            //判断返回的是否是字典
            guard let dict = responseObject as? [String: AnyObject] else{
                print("后台返回的数据格式不对")
                
                //返回的不是字典
                finished(isSucess: false)
                
                return
            }
            
            account.name = dict["name"] as? String
            
            account.avatar_large = dict["avatar_large"] as? String
            
            self.account = account
            
            self.saveAccount(account)
            
            finished(isSucess: true)
            
        }
    }
    //归档用户信息
    private func saveAccount(account: ZJKUserAccount){
        
        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archive")
        
        NSKeyedArchiver.archiveRootObject(account, toFile: path)
    }
    //去沙盒中去读取用户的登录信息
    private func accountInSanBox() -> ZJKUserAccount?{
        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.archive")
        
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? ZJKUserAccount
        
        return result
    }
    
    
}
